package org.daidai.abstrusewriting.homepage;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
 * Created by Administrator on 2016/11/4.
 */

public class HttpUtils {
    private HttpUtils(){}
    public static byte[] doGet(String url){
        byte[] ret=null;
        if (url != null) {


            try {
                URL u  = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) u.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Accept-Encoding", "gzip");

                conn.connect();
                int code = conn.getResponseCode();
                if (code== HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = conn.getInputStream();

                    String encoding = conn.getContentEncoding();

                    // Accept-Encoding 代表能够接受服务器传过来的压缩内容
                    if ("gzip".equals(encoding)) {
                        // 解压缩
                        inputStream = new GZIPInputStream(inputStream);
                    }

                    byte[] buff=new byte[1024];
                    int length;
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    while ((length=inputStream.read(buff))!=-1){
                        out.write(buff,0,length);
                    }
                    ret=out.toByteArray();

                    conn.disconnect();
                    inputStream.close();
                    out.close();

                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

        return  ret;
    }

}
